package com.xiaoming;

import com.xiaoming.utils.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

public class RpcConsumer {
    private static ExecutorService executor = newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;

    public Object createProxy(final Class<?> serviceClass){
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass},
                (Object proxy, Method method, Object[] args) ->{
                    if (userClientHandler ==null){
                        initClient();
                    }

                    //组装RpcRequest对象
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setRequestId("1");
                    rpcRequest.setClassName("com.xiaoming.service.UserServiceImpl");
                    rpcRequest.setMethodName("sayHello");
                    Object[] paraObjArr ={args[0]};
                    rpcRequest.setParameters(paraObjArr);
                    Class[] paraTypeArr ={User.class};
                    rpcRequest.setParameterTypes(paraTypeArr);
                    userClientHandler.setParam(rpcRequest);
                    return executor.submit(userClientHandler).get();
        });
    }



    //2.初始化netty客户端
    public static  void initClient() throws InterruptedException {
        userClientHandler = new UserClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcResponse.class,new JSONSerializer()));
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1",8990).sync();
    }

}
